package com.cskaoyan.controller;

import com.cskaoyan.anno.MyLog;
import com.cskaoyan.bean.ActiveUser;
import com.cskaoyan.bean.user.WxUserLoginData;
import com.cskaoyan.bo.user.UserLoginBo;
import com.cskaoyan.service.user.AuthService;
import com.cskaoyan.service.user.WxUserService;
import com.cskaoyan.token.MallToken;
import com.cskaoyan.vo.BaseRespVo;
import com.cskaoyan.vo.system.AdminInfoVo;
import com.cskaoyan.vo.user.DashBoardVo;
import com.cskaoyan.vo.user.WxUserLoginVo;
import com.cskaoyan.vo.wxorder.IndexOrderVo;
import com.cskaoyan.vo.wxorder.IndexVo;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import com.cskaoyan.bo.user.UserLoginBo;
import com.cskaoyan.vo.BaseRespVo;
import com.cskaoyan.vo.WxAuthLoginVo;
import com.cskaoyan.vo.WxUserIndexVo;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;

@RestController
public class WxAuthController {
    @Autowired
    WxUserService wxUserService;

    @RequestMapping("wx/auth/login")
    public BaseRespVo WxLogin(@RequestBody UserLoginBo userLoginBo) {
        MallToken wxToken = new MallToken(userLoginBo.getUsername(), userLoginBo.getPassword(), "wx");
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(wxToken);
        } catch (Exception e) {
            // 未认证成功则需要跳转到认证页面
            return BaseRespVo.error(700, "账号密码错误");
        }

        // 把sessionID 交给前台维护
        Serializable id = subject.getSession().getId();
        WxUserLoginData wxUserLoginData = (WxUserLoginData) subject.getPrincipal();

        WxUserLoginVo.UserInfoBean userInfoBean = new WxUserLoginVo.UserInfoBean();
        userInfoBean.setNickName(userLoginBo.getUsername());
        userInfoBean.setAvatarUrl(wxUserLoginData.getAvatar());

        WxUserLoginVo wxUserLoginVo = new WxUserLoginVo();
        wxUserLoginVo.setUserInfo(userInfoBean);
        wxUserLoginVo.setToken(id.toString());

        return BaseRespVo.ok(wxUserLoginVo);
    }

    @RequestMapping("wx/auth/logout")
    public BaseRespVo WxLogin() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVo.ok();
    }

    @RequestMapping("/wx/user/index")
    public BaseRespVo index() {
        Subject subject = SecurityUtils.getSubject();
        WxUserLoginData loginData = (WxUserLoginData) subject.getPrincipal();
        Integer userId = loginData.getId();
        IndexOrderVo indexOrderVo = wxUserService.selectOrderInfo(userId);
        return BaseRespVo.ok(new IndexVo(indexOrderVo));
    }

}
